//
//  CZMyTaskDetailViewController.m
//  nsj_iOS
//
//  Created by apple on 2017/1/27.
//  Copyright © 2017年 GCZ. All rights reserved.
//

#import "CZMyTaskDetailViewController.h"
#import "CZMyTaskItemView.h"
#import "CZMyTaskImageCell.h"
#import "CZUploadTaskPicViewController.h"
#import "CZUploadTaskTextViewController.h"
#import "CZUploadTaskVideoViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "CZVideoPlayViewController.h"
#import "SDPhotoBrowser.h"

static NSString *const my_task_detail_cell = @"my_task_detail_cell";
@interface CZMyTaskDetailViewController ()<UIImagePickerControllerDelegate, UINavigationControllerDelegate, UITableViewDelegate, UITableViewDataSource, SDPhotoBrowserDelegate>
@property (weak, nonatomic) IBOutlet UITableView *taskTableView;
@property (nonatomic, strong) NSMutableArray *picArray;
@property (nonatomic, strong) NSMutableArray *videoArray;
@property (nonatomic, copy) NSString *contentText;
@property (nonatomic, copy) NSString *recordId;
@property (nonatomic, copy) NSString *novelTitle;
@property (nonatomic, assign) BOOL isCommit;
@property (weak, nonatomic) IBOutlet UIButton *commitBtn;

//@property (nonatomic, copy) NSString *content;

@end

@implementation CZMyTaskDetailViewController

- (NSMutableArray *__nonnull)videoArray {
    if (!_videoArray) {
        _videoArray = [[NSMutableArray alloc] init];
    }
    return _videoArray;
}

- (NSMutableArray *__nonnull)picArray {
    if (!_picArray) {
        _picArray = [[NSMutableArray alloc] init];
    }
    return _picArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _isCommit = YES;
    self.title = @"任务详情";
    self.contentText = @"";
//    self.automaticallyAdjustsScrollViewInsets = NO;
    [self.taskTableView registerNib:[UINib nibWithNibName:@"CZMyTaskImageCell" bundle:nil] forCellReuseIdentifier:my_task_detail_cell];
    [self postTaskData];
    self.taskTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.taskTableView.estimatedRowHeight = 200;
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"fh"] style:(UIBarButtonItemStylePlain) target:self action:@selector(submitBack)];
    // Do any additional setup after loading the view from its nib.
}

- (void)submitBack {
    if (self.isCommit) {
        [self.navigationController popViewControllerAnimated:YES];
    } else {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"尚未提交作品，是否提交？" preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
            [alertVC dismissViewControllerAnimated:YES completion:nil];
            [self.navigationController popViewControllerAnimated:YES];
        }];
        
        UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"提交" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            [self sendWorks:nil];
            [alertVC dismissViewControllerAnimated:YES completion:nil];
        }];
        [alertVC addAction:action1];
        [alertVC addAction:action2];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
}

- (void)setheaderViewWithDataDic:(NSDictionary *)dic {
    CZMyTaskItemView *headerView = [[NSBundle mainBundle] loadNibNamed:@"CZMyTaskItemView" owner:nil options:nil].firstObject;
    headerView.titleLabel.text = dic[@"task_name"];
    headerView.contentLabel.text = dic[@"content"];
    headerView.titleHeight.constant = [self heightForString:dic[@"task_name"] fontsize:22];
    headerView.contentHeight.constant = [self heightForString:dic[@"content"] fontsize:headerView.contentLabel.font.pointSize];

    headerView.frame = CGRectMake(0, 0, Main_Screen_Width, 562 + headerView.titleHeight.constant + headerView.contentHeight.constant + 64);
    
    NSString *startTime = dic[@"start_date"];
    NSString *endTime = dic[@"end_date"];
    
    NSString *dateTime = [[[startTime substringToIndex:10] stringByAppendingString:@"至"] stringByAppendingString:[endTime substringToIndex:10]];
    headerView.timeLabel.text = dateTime;
    headerView.currencyPrizeLabel.text = dic[@"currency_prize"];
    headerView.experiencePrizeLabel.text = dic[@"experience_prize"];
    NSArray *statusArr = @[@"进行中", @"已完成", @"已奖励", @"不通过", @"逾期"];
    //    NSArray *statusIcons = @[@""];
    NSString *status = dic[@"record_stauts"];
    headerView.taskStautsLabel.text = statusArr[status.integerValue];
    [headerView.submitBtn addTarget:self action:@selector(submitWorks) forControlEvents:(UIControlEventTouchUpInside)];
    [headerView layoutIfNeeded];
    
    UIImageView *imgView = [[UIImageView alloc] init];
    imgView.layer.cornerRadius = 10;
    imgView.clipsToBounds = YES;
    [headerView addSubview:imgView];
    [imgView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.width.height.equalTo(@20);
        make.centerY.equalTo(headerView.taskStarLabel);
        make.right.equalTo(headerView.timeLabel);
    }];
    if (![dic[@"honor_pic"] isKindOfClass:[NSNull class]]) {
        NSURL *honorUrl = [NSURL URLWithString:dic[@"honor_pic"]];
        imgView.yy_imageURL = honorUrl;
    }
    if ([dic[@"record_stauts"] isEqualToString:@"2"]) {
        headerView.submitBtn.enabled = NO;
        headerView.submitBtn.backgroundColor = [UIColor grayColor];
        self.commitBtn.enabled = NO;
        self.commitBtn.backgroundColor = [UIColor grayColor];
    }
    self.taskTableView.tableHeaderView = headerView;
}

- (void)setFootViewWithTitle:(NSString *)title content:(NSString *)content {
    self.novelTitle = title;
    self.contentText = content;
    CGFloat titleHeight = [self heightForString:title fontsize:20];
    CGFloat contentHeight = [self heightForString:content fontsize:14];
    UIView *footView = [[UIView alloc] initWithFrame:CGRectMake(0, 20, Main_Screen_Width, 0)];
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(20, 20, Main_Screen_Width - 40, titleHeight)];
    titleLabel.font = [UIFont systemFontOfSize:20];
    titleLabel.textColor = mRGBColor(97, 97, 97);
    titleLabel.text = title;
    UILabel *contentlabel = [[UILabel alloc] initWithFrame:CGRectMake(20, titleLabel.bottom + 5, Main_Screen_Width - 40, contentHeight)];
    contentlabel.font = [UIFont systemFontOfSize:14];
    contentlabel.textColor = mRGBColor(97, 97, 97);
    contentlabel.text = content;
    footView.height = titleHeight + contentHeight + 20 + 10 + 10;
    
    [footView addSubview:titleLabel];
    [footView addSubview:contentlabel];
    
    
    self.taskTableView.tableFooterView = footView;
}

- (CGFloat)heightForString:(NSString *)string fontsize:(NSInteger)fontsize {

    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle alloc] init];
    NSDictionary *attributes = @{ NSFontAttributeName : [UIFont systemFontOfSize:fontsize], NSParagraphStyleAttributeName : style};
    CGRect bounds = [string boundingRectWithSize:CGSizeMake(Main_Screen_Width - 40, CGFLOAT_MAX) options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading) attributes:attributes context:nil];
    
    //3.返回bounds的高度
    if (bounds.size.height < 30) {
        return 30;
    } else {
        return bounds.size.height + 20;
    }
}


- (void)submitWorks {
//    CZUploadMyTaskViewController *uploadTask = [[CZUploadMyTaskViewController alloc] init];
//    [self.navigationController pushViewController:uploadTask animated:YES];
//    return;
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"提示" message:@"请选择上传类型" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"上传图片" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        CZUploadTaskPicViewController *uploadPicVC = [[CZUploadTaskPicViewController alloc] init];
        uploadPicVC.picArray = self.picArray.mutableCopy;
        uploadPicVC.type = @"picture";
        @weakify(uploadPicVC);
        uploadPicVC.callBack = ^() {
            self.picArray = weak_uploadPicVC.picArray.copy;
            _isCommit = NO;
            [self.taskTableView reloadData];
        };
        [self.navigationController pushViewController:uploadPicVC animated:YES];
        [alertVC dismissViewControllerAnimated:YES completion:nil];
    }];
    
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"上传视频" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        CZUploadTaskVideoViewController *videoVC = [[CZUploadTaskVideoViewController alloc] init];
        videoVC.videoArray = self.videoArray.mutableCopy;
        @weakify(videoVC);
        videoVC.callBack = ^() {
            self.videoArray = weak_videoVC.videoArray;
            _isCommit = NO;
            [self.taskTableView reloadData];
        };
        [self.navigationController pushViewController:videoVC animated:YES];
        [alertVC dismissViewControllerAnimated:YES completion:nil];
    }];
    
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"上传故事" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        CZUploadTaskTextViewController *textVC = [[CZUploadTaskTextViewController alloc] init];
        textVC.novelTitle = self.novelTitle;
        textVC.content = self.contentText;
        textVC.saveTextBlock = ^(NSString *title, NSString *content) {
            _isCommit = NO;
            [self setFootViewWithTitle:title content:content];
        };
        [self.navigationController pushViewController:textVC animated:YES];
        [alertVC dismissViewControllerAnimated:YES completion:nil];
    }];
    
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:^(UIAlertAction * _Nonnull action) {
        [alertVC dismissViewControllerAnimated:YES completion:nil];
    }];
    
    [alertVC addAction:action1];
    [alertVC addAction:action2];
    [alertVC addAction:action3];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
    
}

- (IBAction)sendWorks:(UIButton *)sender {
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/task/my-task-upload",APP_HOST];
    NSMutableDictionary *params = @{@"token" : [[NSUserDefaults standardUserDefaults] objectForKey:User_Token], @"record_id" : self.recordId}.mutableCopy;
    if (self.videoArray.count > 0) {
        NSData *data = [NSJSONSerialization dataWithJSONObject:self.videoArray options:(NSJSONWritingPrettyPrinted) error:nil];
        NSString *videoStr = [[NSString alloc] initWithData:data encoding:(NSUTF8StringEncoding)];
        [params setObject:videoStr forKey:@"works_video"];
    }
    if (self.novelTitle.length > 0) {
        [params setObject:self.novelTitle forKey:@"text_title"];
    }
    if (self.picArray.count > 0) {
        NSData *data = [NSJSONSerialization dataWithJSONObject:self.picArray options:(NSJSONWritingPrettyPrinted) error:nil];
        NSString *picStr = [[NSString alloc] initWithData:data encoding:(NSUTF8StringEncoding)];
        [params setObject:picStr forKey:@"works_pics"];
    }
    if (self.contentText.length > 0) {
        [params setObject:self.contentText forKey:@"works_text"];

    }
    [GCZAFNetWorking POST:urlString params:params success:^(id response) {
        if ([response[@"code"] isEqualToString:@"200"]) {
            [SVProgressHUD showSuccessWithStatus:@"提交成功"];
            _isCommit = YES;
//            [self.navigationController popViewControllerAnimated:YES];
//            [self.taskTableView reloadData];
        } else {
            [SVProgressHUD showErrorWithStatus:response[@"message"]];
        }
        
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];

    }];
}
- (void)showImage:(NSInteger)index {
    SDPhotoBrowser *browser = [[SDPhotoBrowser alloc] init];
    browser.sourceImagesContainerView = self.taskTableView;
    browser.imageCount = self.picArray.count;
    browser.delegate = self;
    browser.currentImageIndex = index;
//    browser.indexLabel.hidden = YES;
    [browser show];
}

-(UIImage *)photoBrowser:(SDPhotoBrowser *)browser placeholderImageForIndex:(NSInteger)index {
    return nil;
}

-(NSURL *)photoBrowser:(SDPhotoBrowser *)browser highQualityImageURLForIndex:(NSInteger)index {
    NSDictionary *dic = self.picArray[index];
    return [NSURL URLWithString:dic[@"pic"]];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return section == 0 ? self.picArray.count : self.videoArray.count;
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CZMyTaskImageCell *cell;
    cell = (CZMyTaskImageCell *)[tableView dequeueReusableCellWithIdentifier:my_task_detail_cell];
    cell.iconView.contentMode = UIViewContentModeScaleAspectFit;
    if (indexPath.section == 0) {
        NSDictionary *dic = self.picArray[indexPath.row];
        cell.iconView.yy_imageURL = [NSURL URLWithString:dic[@"pic"]];
        cell.playView.hidden = YES;
//        cell.iconView.backgroundColor = [UIColor redColor];
    } else {
        NSDictionary *dic = self.videoArray[indexPath.row];
        cell.iconView.yy_imageURL = [NSURL URLWithString:dic[@"image"]];
        cell.playView.hidden = NO;
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        if (tableView == self.taskTableView) {
            if (indexPath.section == 0) {
                [self.picArray removeObjectAtIndex:indexPath.row];
            } else {
                [self.videoArray removeObjectAtIndex:indexPath.row];
            }
            [self.taskTableView beginUpdates];
            [self.taskTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            [self.taskTableView endUpdates];
            _isCommit = NO;
//            [self.taskTableView reloadData];
        }
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 1) {
        NSString *videoURL = self.videoArray[indexPath.row][@"video"];
        CZVideoPlayViewController *vpVC = [[CZVideoPlayViewController alloc] init];
        vpVC.videoURL = videoURL;
        [self.navigationController pushViewController:vpVC animated:YES];
    } else {
        [self showImage:indexPath.row];
    }
}

- (void)postTaskData {
    
    NSString *urlString = [NSString stringWithFormat:@"%@/api/web/index.php/v1/task/my-task-detail",APP_HOST];
    if (![[NSUserDefaults standardUserDefaults] objectForKey:User_Token]) {
        CZBaseTabBarController *rootVC = (CZBaseTabBarController *)[UIApplication sharedApplication].keyWindow.rootViewController;
        CZNavigationController *naviVC = rootVC.childViewControllers[0];
        CZMessionCenterViewController *homeVC = (CZMessionCenterViewController *)naviVC.childViewControllers[0];
        CZNavigationController *mineNC = rootVC.childViewControllers[4];
        CZMineViewController *mineVC = mineNC.childViewControllers[0];
        CZUserLoginViewController * loginVC = [[[CZNsjHelper alloc] init] presentLoginViewControllerWithViewCotroller:self.parentViewController];
        @weakify(mineVC);
        loginVC.callBack = ^(){
            [weak_mineVC getUserData];
            [homeVC setUserIconImage];
            weak_mineVC.userIconImageView.yy_imageURL = [NSURL URLWithString:[[NSUserDefaults standardUserDefaults] objectForKey:User_Logo]];
            [self postTaskData];
        };
        return;
    }
    [SVProgressHUD show];
    [GCZAFNetWorking POST:urlString params:@{@"record_id" : self.record_id, @"token" : [[NSUserDefaults standardUserDefaults] objectForKey:User_Token]} success:^(id response) {
        [SVProgressHUD dismiss];
        if ([response[@"code"] isEqualToString:@"200"]) {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self setheaderViewWithDataDic:response[@"result"]];
                NSString *jsonPicString = response[@"result"][@"works_pics"];
                NSData *jsonPicData = [jsonPicString dataUsingEncoding:NSASCIIStringEncoding];
                NSArray *jsonPicArray = [NSJSONSerialization JSONObjectWithData:jsonPicData options:(NSJSONReadingAllowFragments) error:nil];
                if (jsonPicArray.count > 0) {
                    self.picArray = jsonPicArray.mutableCopy;
                    [self.taskTableView reloadData];
                }

                NSString *jsonVideoString = response[@"result"][@"works_video"];
                NSData *jsonData = [jsonVideoString dataUsingEncoding:NSASCIIStringEncoding];
                NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:jsonData options:(NSJSONReadingAllowFragments) error:nil];
                if (jsonArray.count > 0) {
                    self.videoArray = jsonArray.mutableCopy;
                    [self.taskTableView reloadData];
                }
                
                self.contentText = response[@"result"][@"works_text"];
                if (self.contentText.length > 0) {
                    [self setFootViewWithTitle:response[@"result"][@"text_title"] content:response[@"result"][@"works_text"]];
                }
                self.recordId = response[@"result"][@"record_id"];
                
            });
            
            
        }
    } failure:^(NSURLSessionDataTask *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
    }];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
